﻿using SuperX.Common;
using SuperX.Common.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperX.Helper;
using System.Net.Http;
using System.Xml.Linq;
using SuperX.Helper.ServiceResponse;
using SuperX.Common.APIManager;
using SuperX.PermissionsService.Data;
using Newtonsoft.Json;

namespace SuperX.PermissionsService
{
    [PythonScript(label = "PermissionsController", apply = "PermissionsController", type = "keyword", detail = "")]
    public class PermissionsController : DynamicApiController
    {
        private readonly PermissionsServer _server;
        private readonly IdentityRepository repository;

        public PermissionsController(PermissionsServer server)
        {
            _server = server;
            Name = nameof(PermissionsController);
            repository = new IdentityRepository();
        }

        [WebApi("登录接口", "用户名,密码", "返回String")]
        public ApiResponse<string> Login(string name, string password)
        {
            var user = _server.Config.Users.Where(u => u.Name == name).FirstOrDefault();
            if (user == null || user.Password != Helper.Encryption.Encode(password))
                return ApiResponse<string>.Fail("用户名或密码错误!");
            return ApiResponse<string>.Success("", Guid.NewGuid().ToString());
        }

        [WebApi("获取用户信息", "", "返回用户对象")]
        public ApiResponse<User> GetUser()
        {
            User User = _server.Config.Users.FirstOrDefault();
            return User.ToResponse("成功！");
        }

        [WebApi("获取当前登录的用户信息", "", "返回用户对象")]
        public ApiResponse<Account> GetUserInfo()
        {
            if (repository.Account != null)
            {
                return ApiResponse<Account>.Success("获取成功", repository.Account);
            }
            else
            {
                return ApiResponse<Account>.Fail("获取失败，请先登录");
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="name">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [WebApi("登录接口", "用户名,密码", "操作结果")]
        public ApiResponse<Account> Login2(string name, string password)
        {
            if (repository.Login(name, password))
            {
                var account = repository.GetAccount(name);
                Common.User.UserService.GetInstance().Account = new SuperX.Common.User.Account()
                {
                    UserName = account.UserName,
                    Password = account.Password,
                    Name = account.Name,
                    RoleName = account.RoleName,
                    RegisterTime = account.RegisterTime,
                };
                if (!string.IsNullOrWhiteSpace(account.RoleName))
                {
                    return ApiResponse<Account>.Success("登录成功", account);
                }
                return ApiResponse<Account>.Success("登录成功");
            }
            else
            {
                return ApiResponse<Account>.Fail("登录失败");
            }
        }

        /// <summary>
        /// 账号注册
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="name">姓名</param>
        /// <param name="password">密码</param>
        /// <param name="confirmPassword">确认密码</param>
        /// <param name="roleName">角色名称</param>
        /// <returns></returns>
        [WebApi("账号注册", "用户名,密码,确认密码，角色名称", "操作结果")]
        public ApiResponse<string> RegisterAccount(string userName, string name, string password, string confirmPassword, string roleName = null)
        {
            var account = repository.GetAccount(userName);
            if (account != null)
            {
                return ApiResponse<string>.Fail("已存在相同名称的账号");
            }
            if (password != confirmPassword)
            {
                return ApiResponse<string>.Fail("密码和确认密码不一致");
            }
            if (!string.IsNullOrWhiteSpace(roleName))
            {
                var role = repository.GetRole(roleName);
                if (role == null)
                {
                    return ApiResponse<string>.Fail("无效的角色名称");
                }
            }
            if (repository.Register(userName, name, password, roleName))
            {
                return ApiResponse<string>.Success("注册成功");
            }
            else
            {
                return ApiResponse<string>.Fail("注册失败");
            }
        }

        /// <summary>
        /// 取消注册
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        [WebApi("取消注册", "用户名", "操作结果")]
        public ApiResponse<string> UnregisterAccount(string userName)
        {
            var account = repository.GetAccount(userName);
            if (account == null)
            {
                return ApiResponse<string>.Fail("账号不存在");
            }
            if (repository.Unregister(userName))
            {
                return ApiResponse<string>.Success("取消注册成功");
            }
            else
            {
                return ApiResponse<string>.Fail("取消注册失败");
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="confirmPassword">确认密码</param>
        /// <returns></returns>
        [WebApi("修改密码", "用户名,姓名,密码,确认密码", "操作结果")]
        public ApiResponse<string> ResetPassword(string userName, string password, string confirmPassword)
        {
            var account = repository.GetAccount(userName);
            if (account == null)
            {
                return ApiResponse<string>.Fail("账号不存在");
            }
            if (password != confirmPassword)
            {
                return ApiResponse<string>.Fail("密码和确认密码不一致");
            }
            if (repository.ChangePassword(userName, password))
            {
                return ApiResponse<string>.Success("修改密码成功");
            }
            else
            {
                return ApiResponse<string>.Fail("修改密码失败");
            }
        }

        /// <summary>
        /// 查询账号列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="pageSize">页面大小</param>
        /// <returns></returns>
        [WebApi("查询账号列表", "页码,页面大小", "操作结果")]
        public ApiResponse<ResponseList<Account>> QueryAccounts(int page = 1, int pageSize = 10)
        {
            var accounts = repository.GetAllAccounts(page, pageSize);
            var response = new ResponseList<Account>()
            {
                TotalCount = repository.GetAccountCount(),
                CurrentPage = page,
                PageSize = pageSize,
                Items = accounts
            };
            return ApiResponse<ResponseList<Account>>.Success("查询账号列表成功", response);
        }

        /// <summary>
        /// 设置角色
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="roleName">角色名称</param>
        /// <returns></returns>
        [WebApi("设置角色", "用户名,角色名称", "操作结果")]
        public ApiResponse<string> SetRole(string userName, string roleName)
        {
            var account = repository.GetAccount(userName);
            if (account == null)
            {
                return ApiResponse<string>.Fail("账号不存在");
            }
            if (!string.IsNullOrWhiteSpace(roleName))
            {
                var role = repository.GetRole(roleName);
                if (role == null)
                {
                    return ApiResponse<string>.Fail("无效的角色名称");
                }
            }
            if (repository.SetAccountRole(userName, roleName))
            {
                return ApiResponse<string>.Success("设置角色成功");
            }
            else
            {
                return ApiResponse<string>.Fail("设置角色失败");
            }
        }

        /// <summary>
        /// 查询账号
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        [WebApi("查询账号", "用户名", "操作结果")]
        public ApiResponse<Account> GetAccount(string userName)
        {
            var account = repository.GetAccount(userName);
            if (account == null)
            {
                return ApiResponse<Account>.Fail("账号不存在");
            }
            Common.User.UserService.GetInstance().Account = new Common.User.Account()
            {
                UserName = account.UserName,
                Password = account.Password,
                Name = account.Name,
                RoleName = account.RoleName,
                RegisterTime = account.RegisterTime,
            };
            return ApiResponse<Account>.Success("查询账号成功", account);
        }

        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="name">角色名称</param>
        /// <param name="description">描述</param>
        /// <param name="functionMenu">功能菜单</param>
        /// <returns></returns>
        [WebApi("创建角色", "角色名称,描述,功能菜单", "操作结果")]
        public ApiResponse<string> CreateRole(string name, string description = null, string functionMenu = null)
        {
            var role = repository.GetRole(name);
            if (role != null)
            {
                return ApiResponse<string>.Fail("该角色已经存在");
            }
            if (repository.CreateRole(name, description, functionMenu))
            {
                return ApiResponse<string>.Success("创建角色成功");
            }
            else
            {
                return ApiResponse<string>.Fail("创建角色失败");
            }
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="name">角色名称</param>
        /// <returns></returns>
        [WebApi("删除角色", "角色名称", "操作结果")]
        public ApiResponse<string> DeleteRole(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return ApiResponse<string>.Fail("角色不存在");
            }
            var role = repository.GetRole(name);
            if (role == null)
            {
                return ApiResponse<string>.Fail("角色不存在");
            }
            if (repository.DeleteRole(name))
            {
                return ApiResponse<string>.Success("删除角色成功");
            }
            else
            {
                return ApiResponse<string>.Fail("删除角色失败");
            }
        }

        /// <summary>
        /// 更新角色
        /// </summary>
        /// <param name="name">角色名称</param>
        /// <param name="description">描述</param>
        /// <param name="FunctionMenu">功能菜单</param>
        /// <returns></returns>
        [WebApi("更新角色", "角色名称", "操作结果")]
        public ApiResponse<string> UpdateRole(string name, string description = null, string functionMenu = null)
        {
            var role = repository.GetRole(name);
            if (role == null)
            {
                return ApiResponse<string>.Fail("角色不存在");
            }
            if (repository.UpdateRole(name, description, functionMenu))
            {
                return ApiResponse<string>.Success("更新角色成功");
            }
            else
            {
                return ApiResponse<string>.Fail("更新角色失败");
            }
        }

        /// <summary>
        /// 查询角色
        /// </summary>
        /// <param name="name">角色名称</param>
        /// <returns></returns>
        [WebApi("查询角色", "角色名称", "操作结果")]
        public ApiResponse<Role> GetRole(string name)
        {
            var role = repository.GetRole(name);
            if (role == null)
            {
                return ApiResponse<Role>.Fail("角色不存在");
            }
            return ApiResponse<Role>.Success("查询角色成功", role);
        }

        /// <summary>
        /// 查询角色列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="pageSize">页面大小</param>
        /// <returns></returns>
        [WebApi("查询角色列表", "页码,页面大小", "操作结果")]
        public ApiResponse<ResponseList<Role>> QueryRoles(int page = 1, int pageSize = 10)
        {
            var roles = repository.GetAllRoles(page, pageSize);
            var response = new ResponseList<Role>()
            {
                TotalCount = repository.GetRoleCount(),
                CurrentPage = page,
                PageSize = pageSize,
                Items = roles
            };
            return ApiResponse<ResponseList<Role>>.Success("查询角色列表成功", response);
        }
    }
}